package com.qianfeng.gl4study.youshare.tasks;

import android.os.AsyncTask;
import android.provider.ContactsContract;
import com.qianfeng.gl4study.youshare.utils.Constants;
import com.qianfeng.gl4study.youshare.utils.HttpTool;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * 获取产品列表的接口调用
 *  用于核心产品和平台产品中
 * Created with IntelliJ IDEA.
 * I'm glad to share my knowledge with you all.
 * User:Gaolei
 * Date:2015/2/5
 * Email:pdsfgl@live.com
 */
public class ProductListTask extends AsyncTask<String ,Integer,JSONObject> {


	private TaskProcessor processor;

	public ProductListTask(TaskProcessor processor) {
		this.processor = processor;
	}

	@Override
	protected JSONObject doInBackground(String... params) {

		JSONObject ret = null;
		if(params!=null&&params.length>=1) {
			//指定分类ID，用于获取不同分类的产品
			String id = "0";
			String size = "5";
			String page = "1";

			switch (params.length){
				case 3:
					page = params[2];
				case 2:
					size = params[1];
				case 1:
					id = params[0];
					break;
			}
			String url = Constants.API_POINT +
					"/category.php?id=" + id
					+"&size=" +size
					+"&page="+page;
			byte[] bytes = HttpTool.get(url);
			if(bytes!=null){
				try {
					String str = new String(bytes, "UTF-8");
					ret = new JSONObject(str);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		return ret;
	}

	@Override
	protected void onPostExecute(JSONObject jsonObject) {
		if (processor!=null&&jsonObject!=null){
			processor.processResult(jsonObject,2);
		}

	}
}
